<template>
  <div class="location-page">
    <div class="page-header">
      <h1 class="title">微信定位</h1>
      <p class="subtitle">获取用户地理位置信息</p>
    </div>

    <div class="container">
      <div class="location-content">
        <!-- 位置信息显示 -->
        <div v-if="locationInfo" class="location-info">
          <div class="location-card">
            <h2>当前位置信息</h2>
            <div class="location-details">
              <div class="detail-item">
                <label>经度:</label>
                <span>{{ locationInfo.longitude }}</span>
              </div>
              <div class="detail-item">
                <label>纬度:</label>
                <span>{{ locationInfo.latitude }}</span>
              </div>
              <div class="detail-item">
                <label>详细地址:</label>
                <span>{{ locationInfo.address }}</span>
              </div>
              <div class="detail-item">
                <label>城市:</label>
                <span>{{ locationInfo.city }}</span>
              </div>
              <div class="detail-item">
                <label>省份:</label>
                <span>{{ locationInfo.province }}</span>
              </div>
            </div>
            <div class="location-actions">
              <button @click="refreshLocation" class="btn btn-primary" :disabled="isLoading">
                {{ isLoading ? '获取中...' : '刷新位置' }}
              </button>
              <button @click="clearLocation" class="btn btn-secondary">
                清除位置
              </button>
            </div>
          </div>
        </div>

        <!-- 获取位置 -->
        <div v-else class="location-getter">
          <div class="location-card">
            <div class="location-icon">
              <div class="location-symbol">📍</div>
            </div>
            <h2>获取位置信息</h2>
            <p class="location-desc">点击下方按钮获取您的地理位置信息</p>
            
            <button 
              @click="getLocation" 
              class="btn btn-primary location-btn"
              :disabled="isLoading"
            >
              <span v-if="isLoading" class="spinner"></span>
              {{ isLoading ? '获取中...' : '获取位置信息' }}
            </button>

            <div class="location-tips">
              <h3>位置服务说明：</h3>
              <ul>
                <li>• 需要您授权位置访问权限</li>
                <li>• 位置信息仅用于提供服务</li>
                <li>• 您可以随时清除位置信息</li>
                <li>• 位置数据安全加密传输</li>
              </ul>
            </div>
          </div>
        </div>

        <!-- 地图显示 -->
        <div v-if="locationInfo" class="map-section">
          <h2>位置地图</h2>
          <div class="map-container">
            <div class="map-placeholder">
              <div class="map-icon">🗺️</div>
              <p>地图显示区域</p>
              <p class="map-coords">
                经度: {{ locationInfo.longitude }}<br>
                纬度: {{ locationInfo.latitude }}
              </p>
            </div>
          </div>
        </div>

        <!-- 位置历史 -->
        <div class="location-history">
          <h2>位置历史</h2>
          <div v-if="locationHistory.length === 0" class="empty-state">
            <p>暂无位置记录</p>
          </div>
          <div v-else class="history-list">
            <div
              v-for="(location, index) in locationHistory"
              :key="index"
              class="history-item"
            >
              <div class="location-preview">
                <div class="location-symbol-small">📍</div>
              </div>
              <div class="location-details-small">
                <h3>{{ location.address }}</h3>
                <p class="location-meta">
                  {{ location.city }}, {{ location.province }}
                </p>
                <p class="location-coords">
                  经度: {{ location.longitude }}, 纬度: {{ location.latitude }}
                </p>
                <p class="location-time">
                  {{ formatTime(location.timestamp) }}
                </p>
              </div>
              <div class="location-actions-small">
                <button @click="setCurrentLocation(location)" class="btn btn-secondary">
                  设为当前位置
                </button>
                <button @click="deleteLocation(index)" class="btn btn-danger">
                  删除
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useWeChatStore } from '@/stores/wechat'
import { wechatApi } from '@/api/wechat'
import type { LocationInfo } from '@/types'

const wechatStore = useWeChatStore()

const isLoading = ref(false)
const locationHistory = ref<(LocationInfo & { timestamp: string })[]>([])

const locationInfo = computed(() => wechatStore.locationInfo)

const getLocation = async () => {
  isLoading.value = true
  try {
    // 尝试使用浏览器原生定位API
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        async (position) => {
          const mockLocation: LocationInfo = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            address: '通过GPS获取的位置',
            city: '深圳',
            province: '广东'
          }
          
          wechatStore.setLocation(mockLocation)
          
          // 添加到历史记录
          locationHistory.value.unshift({
            ...mockLocation,
            timestamp: new Date().toISOString()
          })
          
          alert('位置获取成功！')
          isLoading.value = false
        },
        (error) => {
          console.error('定位失败:', error)
          // 使用模拟数据
          useMockLocation()
        }
      )
    } else {
      // 使用模拟数据
      useMockLocation()
    }
  } catch (error) {
    console.error('获取位置失败:', error)
    useMockLocation()
  }
}

const useMockLocation = () => {
  const mockLocation: LocationInfo = {
    latitude: 22.5431 + Math.random() * 0.01,
    longitude: 114.0579 + Math.random() * 0.01,
    address: '深圳市南山区科技园',
    city: '深圳',
    province: '广东'
  }
  
  wechatStore.setLocation(mockLocation)
  
  // 添加到历史记录
  locationHistory.value.unshift({
    ...mockLocation,
    timestamp: new Date().toISOString()
  })
  
  alert('模拟位置获取成功！')
  isLoading.value = false
}

const refreshLocation = () => {
  getLocation()
}

const clearLocation = () => {
  wechatStore.setLocation(null)
  alert('位置信息已清除')
}

const setCurrentLocation = (location: LocationInfo & { timestamp: string }) => {
  wechatStore.setLocation(location)
  alert('已设为当前位置')
}

const deleteLocation = (index: number) => {
  if (confirm('确定要删除这个位置记录吗？')) {
    locationHistory.value.splice(index, 1)
  }
}

const formatTime = (timeString: string) => {
  return new Date(timeString).toLocaleString('zh-CN')
}

onMounted(() => {
  // 模拟加载位置历史
  const mockLocations: (LocationInfo & { timestamp: string })[] = [
    {
      latitude: 22.5431,
      longitude: 114.0579,
      address: '深圳市南山区科技园',
      city: '深圳',
      province: '广东',
      timestamp: new Date(Date.now() - 3600000).toISOString()
    },
    {
      latitude: 22.5431,
      longitude: 114.0579,
      address: '深圳市福田区中心区',
      city: '深圳',
      province: '广东',
      timestamp: new Date(Date.now() - 7200000).toISOString()
    }
  ]
  
  locationHistory.value = mockLocations
})
</script>

<style scoped>
.location-page {
  min-height: 100vh;
  position: relative;
}

.page-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 0 0 30px 30px;
  margin-bottom: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 2.5rem;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 16px;
}

.subtitle {
  font-size: 1.2rem;
  color: #666;
  max-width: 600px;
  margin: 0 auto;
}

.location-content {
  max-width: 1200px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
}

.location-info,
.location-getter,
.map-section,
.location-history {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.location-info h2,
.location-getter h2,
.map-section h2,
.location-history h2 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
  text-align: center;
}

.location-details {
  margin-bottom: 24px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item label {
  font-weight: 500;
  color: #333;
  min-width: 80px;
}

.detail-item span {
  color: #666;
  font-family: monospace;
  font-size: 0.9rem;
  text-align: right;
  flex: 1;
}

.location-actions {
  display: flex;
  gap: 12px;
}

.location-actions .btn {
  flex: 1;
}

.location-icon {
  text-align: center;
  margin-bottom: 20px;
}

.location-symbol {
  width: 80px;
  height: 80px;
  background: #607d8b;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2.5rem;
  margin: 0 auto;
  box-shadow: 0 8px 20px rgba(96, 125, 139, 0.3);
}

.location-getter h2 {
  font-size: 1.8rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  text-align: center;
}

.location-desc {
  color: #666;
  margin-bottom: 30px;
  font-size: 1.1rem;
  text-align: center;
}

.location-btn {
  width: 100%;
  max-width: 300px;
  padding: 16px;
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0 auto 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.location-tips {
  text-align: left;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
}

.location-tips h3 {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.location-tips ul {
  list-style: none;
  padding: 0;
}

.location-tips li {
  color: #666;
  margin-bottom: 8px;
  font-size: 0.95rem;
}

.map-container {
  height: 300px;
  border-radius: 12px;
  overflow: hidden;
}

.map-placeholder {
  width: 100%;
  height: 100%;
  background: #f0f0f0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
}

.map-icon {
  font-size: 3rem;
  margin-bottom: 12px;
}

.map-coords {
  font-family: monospace;
  font-size: 0.9rem;
  text-align: center;
  margin-top: 8px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.history-list {
  max-height: 400px;
  overflow-y: auto;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  margin-bottom: 12px;
  background: #f9f9f9;
}

.location-preview {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.location-symbol-small {
  font-size: 1.5rem;
}

.location-details-small {
  flex: 1;
  min-width: 0;
}

.location-details-small h3 {
  font-size: 1rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.location-meta {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 4px;
}

.location-coords {
  font-size: 0.8rem;
  color: #999;
  font-family: monospace;
  margin-bottom: 4px;
}

.location-time {
  font-size: 0.8rem;
  color: #999;
}

.location-actions-small {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.location-actions-small .btn {
  padding: 6px 12px;
  font-size: 0.8rem;
  min-width: 80px;
}

.btn-danger {
  background: #fa5151;
  color: white;
}

.btn-danger:hover {
  background: #e74c3c;
}

@media (max-width: 768px) {
  .location-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .title {
    font-size: 2rem;
  }
  
  .subtitle {
    font-size: 1rem;
  }
  
  .location-actions {
    flex-direction: column;
  }
  
  .history-item {
    flex-direction: column;
    text-align: center;
  }
  
  .location-actions-small {
    flex-direction: row;
    justify-content: center;
  }
}
</style>
